//
//  BZThreadManager.m
//  MZBasic
//
//  Created by Sings on 2023/7/6.
//

#import "BZThreadManager.h"
#import "BZThreadQueue.h"
#import "BZThreadGroup.h"

@interface BZThreadManager ()

@property (nonatomic, strong) NSMapTable *mdicGroup;

@property (nonatomic, strong) NSMutableArray *marrGroup;

@end

static BZThreadManager *_threadManager = nil;

@implementation BZThreadManager

- (NSMapTable *) mdicGroup {
    if (_mdicGroup == nil) {
        _mdicGroup = [NSMapTable strongToWeakObjectsMapTable];
    }
    return _mdicGroup;
}

- (NSMutableArray *) marrGroup {
    if (_marrGroup == nil) {
        _marrGroup = [NSMutableArray array];
    }
    return _marrGroup;
}

+ (instancetype) sharedInstance {
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        _threadManager = [[super allocWithZone:NULL] init];
    });
    
    return _threadManager;
}

+ (instancetype) allocWithZone:(struct _NSZone *)zone {
    return [BZThreadManager sharedInstance];
}

- (id) mutableCopy {
    return _threadManager;
}

- (id) copy {
    return _threadManager;
}

- (void) addThreadQueue:(BZThreadQueue *) queue {
    BZThreadGroup *group  = nil;
    if ([self.mdicGroup objectForKey:queue.strLabel] == nil) {
        group = [[BZThreadGroup alloc] initWithiConcurrency:queue.iConcurrency];
        __weak typeof(self) weakSelf = self;
        __weak typeof(group) weakGroup = group;
        group.finished = ^{
//            [weakSelf.mdicGroup removeObjectForKey:queue.strLabel];
//            if (weakSelf.mdicGroup[queue.strLabel]) {
////                weakSelf.mdicGroup[queue.strLabel] = nil;
//                [mapTable removeObjectForKey:key];
//            }
            if ([weakSelf.marrGroup containsObject:weakGroup]) {
                [weakSelf.marrGroup removeObject:weakGroup];
            }
            NSLog(@"---%@ queue_group finished",queue.strLabel);
        };
        [self.marrGroup addObject:group];
//        self.mdicGroup[queue.strLabel] = group;
        [self.mdicGroup setObject:group forKey:queue.strLabel];
    }
    group = [self.mdicGroup objectForKey:queue.strLabel];
    [group addThreadQueue:queue];
}

- (BOOL) queueIsExistWithLabel:(NSString *) queueLabel {
    if ([self.mdicGroup objectForKey:queueLabel] == nil) {
        return NO;
    }else {
        return YES;
    }
}

- (void) stopGroupWithQueueLabel:(NSString *) queueLabel {
    BZThreadGroup *group = [self.mdicGroup objectForKey:queueLabel];
    if (group) {
        [self.mdicGroup removeObjectForKey:queueLabel];
        [group stopAll];
    }
}


@end
